package com.collabscm.pf.web.ext;

import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.struts2.ServletActionContext;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;

import com.collabscm.pf.AbstractTestCase;
import com.collabscm.pf.util.JsonUtils;
import com.collabscm.pf.validation.BeanValidationFailure;
import com.collabscm.pf.validation.BeanValidationUtils;
import com.collabscm.pf.vo.FailureResponse;
import com.opensymphony.xwork2.ActionContext;

@ContextConfiguration(locations={"classpath:config/application-config.xml"})
public class TestValidationFailtureResult extends AbstractTestCase {
	
	@Test
	public void testResponseValidationFailure() throws Exception {
		HttpServletResponse response = new MockResponse() {
		};
		ActionContext context = new ActionContext(new HashMap<String, Object>());
		ServletActionContext.setContext(context);
		ServletActionContext.setResponse(response);
		TestBean tb = new TestBean();
		AObject a = new AObject();
		a.setBean(tb);
		BeanValidationFailure failure = null;
		try {
			BeanValidationUtils.validate(a);
		} catch (BeanValidationFailure f) {
			failure = f;
			failure.setRootBean("a");
		}
		ValidationFailtureResult result = new ValidationFailtureResult();
		result.responseValidationFailure(failure);
	}

	@Test
	public void testFillFailureResponse() {
		TestBean tb = new TestBean();
		AObject a = new AObject();
		a.setBean(tb);
		BeanValidationFailure failure = null;
		try {
			BeanValidationUtils.validate(a);
		} catch (BeanValidationFailure f) {
			failure = f;
			failure.setRootBean("a");
		}
		ValidationFailtureResult result = new ValidationFailtureResult();
		FailureResponse fr = result.fillFailureResponse(failure);
		String jsonString = JsonUtils.toJsonObjectString(fr);
		logger.debug("JSON:{}", jsonString);
	}
	
	/**
	 * 待测试的Bean
	 */
	public static class TestBean {
		@NotNull
		private String userCode;
		@NotNull
		private String userName;
		
		public String getUserCode() {
			return userCode;
		}
		public void setUserCode(String userCode) {
			this.userCode = userCode;
		}
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
	}
	
	public static class AObject {
		@NotNull
		@Valid
		private TestBean bean;

		public TestBean getBean() {
			return bean;
		}

		public void setBean(TestBean bean) {
			this.bean = bean;
		}
		
	}

}
